package com.mmsj;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.OpenableColumns;
import android.widget.Toast;
import androidx.documentfile.provider.DocumentFile;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VttToLrcConverter extends AsyncTask<Void, Void, Integer> {

    private final Context context;
    private final List<Uri> uris;
    private final Uri outputDirUri;
    private final Runnable onFinished;
    private int failCount = 0;
    private StringBuilder failFiles = new StringBuilder();

    public VttToLrcConverter(Context context, List<Uri> uris, Uri outputDirUri, Runnable onFinished) {
        this.context = context;
        this.uris = uris;
        this.outputDirUri = outputDirUri;
        this.onFinished = onFinished;
    }

    @Override
    protected Integer doInBackground(Void... voids) {
        int successCount = 0;
        for (Uri uri : uris) {
            try {
                String vttContent = readVttFile(uri);
                String lrcContent = convertVttToLrc(vttContent);
                if (lrcContent.trim().isEmpty()) {
                    failCount++;
                    failFiles.append(getFileName(uri)).append("\n");
                    continue;
                }
                String lrcFileName = getLrcFileName(uri);
                Uri lrcUri = createLrcFileInOutputDir(lrcFileName);
                if (lrcUri != null) {
                    writeToFile(lrcUri, lrcContent);
                    successCount++;
                } else {
                    // fallback: MediaStore
                    lrcUri = createSiblingFile(uri, lrcFileName);
                    if (lrcUri != null) {
                        writeToFile(lrcUri, lrcContent);
                        successCount++;
                    } else {
                        failCount++;
                        failFiles.append(getFileName(uri)).append("\n");
                    }
                }
            } catch (Exception e) {
                failCount++;
                failFiles.append(getFileName(uri)).append("\n");
                e.printStackTrace();
            }
        }
        return successCount;
    }

    // 读取VTT文件内容
    private String readVttFile(Uri uri) throws Exception {
        ContentResolver resolver = context.getContentResolver();
        try (InputStream inputStream = resolver.openInputStream(uri);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();
        }
    }

    // VTT转LRC核心逻辑，支持多种VTT格式
    private String convertVttToLrc(String vttContent) {
        StringBuilder lrc = new StringBuilder();
        String[] lines = vttContent.split("\n");
        Pattern timePattern = Pattern.compile(
                "(\\d{2}:\\d{2}:\\d{2}\\.\\d{3}|\\d{2}:\\d{2}\\.\\d{3})\\s*-->\\s*(\\d{2}:\\d{2}:\\d{2}\\.\\d{3}|\\d{2}:\\d{2}\\.\\d{3})",
                Pattern.CASE_INSENSITIVE
        );
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();
            // 跳过无效行（WEBVTT、NOTE、STYLE、纯数字、空行等）
            if (line.isEmpty() || line.equalsIgnoreCase("WEBVTT") || line.startsWith("NOTE") || line.startsWith("STYLE") || line.matches("^\\d+$")) {
                continue;
            }
            Matcher matcher = timePattern.matcher(line);
            if (matcher.find()) {
                String startTime = vttTimeToLrc(matcher.group(1));
                // 找到下一个非空、非数字的行作为歌词
                String lyric = "";
                int j = i + 1;
                while (j < lines.length) {
                    String nextLine = lines[j].trim();
                    if (nextLine.isEmpty() || nextLine.matches("^\\d+$")) {
                        j++;
                    } else {
                        lyric = nextLine;
                        break;
                    }
                }
                if (!lyric.isEmpty() && startTime != null) {
                    lrc.append(startTime).append(lyric).append("\n");
                }
            }
        }
        return lrc.toString();
    }

    // VTT时间转LRC时间，支持带小时和不带小时
    private String vttTimeToLrc(String vttTime) {
        Pattern p = Pattern.compile(
                "(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{3})|(\\d{2}):(\\d{2})\\.(\\d{3})"
        );
        Matcher m = p.matcher(vttTime);
        if (!m.matches()) return null;
        String hours, minutes, sec, ms;
        if (m.group(1) != null) { // 带小时
            hours = m.group(1);
            minutes = m.group(2);
            sec = m.group(3);
            ms = m.group(4);
        } else { // 不带小时
            hours = "00";
            minutes = m.group(5);
            sec = m.group(6);
            ms = m.group(7);
        }
        return String.format("[%s:%s:%s.%s]", hours, minutes, sec, ms.substring(0, 2));
    }

    // 获取原文件名
    private String getFileName(Uri uri) {
        String fileName = "converted.vtt";
        ContentResolver resolver = context.getContentResolver();
        try (Cursor cursor = resolver.query(uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int displayNameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                if (displayNameIndex >= 0) {
                    fileName = cursor.getString(displayNameIndex);
                }
            }
        }
        return fileName;
    }

    // 获取健壮的LRC输出文件名，兼容各种VTT后缀
    private String getLrcFileName(Uri uri) {
        String fileName = getFileName(uri);
        // 支持 .vtt/.VTT/.WebVTT/.webvtt 等
        return fileName.replaceFirst("(?i)\\.(vtt|webvtt)$", "") + ".lrc";
    }

    // 用SAF在outputDirUri下创建LRC文件
    private Uri createLrcFileInOutputDir(String lrcFileName) {
        if (outputDirUri == null) return null;
        androidx.documentfile.provider.DocumentFile outputDir = androidx.documentfile.provider.DocumentFile.fromTreeUri(context, outputDirUri);
        if (outputDir == null || !outputDir.canWrite()) return null;
        // 若已存在同名文件，先删除
        androidx.documentfile.provider.DocumentFile existing = outputDir.findFile(lrcFileName);
        if (existing != null) existing.delete();
        // 使用application/octet-stream避免自动加.txt
        androidx.documentfile.provider.DocumentFile lrcFile = outputDir.createFile("application/octet-stream", lrcFileName);
        return lrcFile != null ? lrcFile.getUri() : null;
    }

    // fallback: MediaStore原有目录
    private Uri createSiblingFile(Uri vttUri, String lrcFileName) {
        ContentResolver resolver = context.getContentResolver();
        String relativePath = null;
        try (Cursor cursor = resolver.query(vttUri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int pathIndex = cursor.getColumnIndex(android.provider.MediaStore.MediaColumns.RELATIVE_PATH);
                if (pathIndex >= 0) {
                    relativePath = cursor.getString(pathIndex);
                }
            }
        }
        if (relativePath == null) {
            relativePath = android.os.Environment.DIRECTORY_DOWNLOADS + "/";
        }
        android.content.ContentValues values = new android.content.ContentValues();
        values.put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, lrcFileName);
        values.put(android.provider.MediaStore.MediaColumns.MIME_TYPE, "text/plain");
        values.put(android.provider.MediaStore.MediaColumns.RELATIVE_PATH, relativePath);
        Uri collection = android.provider.MediaStore.Files.getContentUri("external");
        return resolver.insert(collection, values);
    }

    // 写入LRC内容到目标文件
    private void writeToFile(Uri uri, String content) throws Exception {
        ContentResolver resolver = context.getContentResolver();
        try (OutputStream os = resolver.openOutputStream(uri)) {
            if (os != null) {
                os.write(content.getBytes());
            }
        }
    }

    @Override
    protected void onPostExecute(Integer successCount) {
        if (failCount > 0) {
            Toast.makeText(context, "转换完成！成功：" + successCount + "，失败：" + failCount + "\n失败文件：\n" + failFiles, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "转换完成！成功转换 " + successCount + " 个文件", Toast.LENGTH_LONG).show();
        }
        if (onFinished != null) {
            onFinished.run();
        }
    }
}